
#import "ComparePriceViewController.h"
#import "NSString+VoiceOver.h"
#import "UIFont+BoldFont.h"

@interface ComparePriceViewController () <UIPickerViewDelegate, UIPickerViewDataSource, UIPickerViewAccessibilityDelegate> {
    SavingsCalculator *savingsCalculator;
    NSMutableArray *prices;
}

@property (weak, nonatomic) IBOutlet UIPickerView *pickerView;
@property (weak, nonatomic) IBOutlet UILabel *lampLabel;
@property (weak, nonatomic) IBOutlet UILabel *savingsLabel;
@property (weak, nonatomic) IBOutlet UILabel *costLabel;
@property (weak, nonatomic) IBOutlet UIButton *resetButton;
@property (weak, nonatomic) IBOutlet UIButton *resetButtonLandscape;
@property (strong, nonatomic) IBOutlet UIView *separatorViewHorizontal;

@end


@implementation ComparePriceViewController

- (instancetype)initWithSavingsCalculator:(SavingsCalculator *)calculator
{
    self = [super initWithNibName:nil bundle:nil];
    if (self) {
        savingsCalculator = calculator;
        prices = [NSMutableArray array];
        for (NSInteger i = 5; i <= 400; i += (i < 200 ? 5 : 10)) {
            [prices addObject:[NSString stringWithFormat:@"%ld", (long)i]];
        }
    }
    return self;
}

- (void)updatePickerWheelAnimated:(BOOL)animated
{
    float purchasePrice = [savingsCalculator purchasePriceForSubstituteAtIndex:self.subtituteIndex];
    NSInteger pickerindex = [prices indexOfObject:[NSString stringWithFormat:@"%.0f", purchasePrice]];
    [self.pickerView selectRow:pickerindex inComponent:0 animated:animated];
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self updateViewForOrientation:[UIApplication sharedApplication].statusBarOrientation];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.resetButton.layer.borderColor = kNavBarTintColor.CGColor;
    self.resetButton.layer.borderWidth = 1;
    self.resetButton.layer.cornerRadius = 6;
    
    self.resetButtonLandscape.layer.borderColor = kNavBarTintColor.CGColor;
    self.resetButtonLandscape.layer.borderWidth = 1;
    self.resetButtonLandscape.layer.cornerRadius = 6;
    
    [self.pickerView reloadAllComponents];
    
    [self updatePickerWheelAnimated:NO];

    [self updateSavingsLabel];
    [self updateCostLabel];
    
    self.lampLabel.text = self.lampString;
}

-(void)updateViewForOrientation:(UIInterfaceOrientation)orientation {
    if (UIInterfaceOrientationIsPortrait(orientation)) {
        self.resetButton.alpha = 1;
        self.separatorViewHorizontal.alpha = 1;
        self.resetButtonLandscape.alpha = 0;
    } else {
        self.resetButton.alpha = 0;
        self.separatorViewHorizontal.alpha = 0;
        self.resetButtonLandscape.alpha = 1;
    }
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - actions
- (void)donePressed
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)resetButtonPressed {
    [savingsCalculator resetPurchasePriceForSubstituteAtIndex:self.subtituteIndex];
    [self updatePickerWheelAnimated:YES];
    [self updateSavingsLabel];
    [self updateCostLabel];
}

#pragma mark - Picker view data source
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return prices.count;
}

#pragma mark - Picker view delegate
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view {
    UILabel *label = (id)view;
    if (![label isKindOfClass:[UILabel class]]) {
        label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 40, 37)];
        label.font = [UIFont fontWithName:@"HelveticaNeue" size:20];
        label.textAlignment = NSTextAlignmentRight;
        label.backgroundColor = [UIColor clearColor];
    }

    label.text = prices[row];
    if (voiceoverEnabled) {
        float savings = [savingsCalculator savingsForSubstituteAtIndex:self.subtituteIndex usePurchasePrice:[prices[row] floatValue]];
        if (savings <= 0) {
            label.accessibilityLabel = [NSString stringWithFormat:@"%@-lampan kostar %@ kronor, du sparar då inga pengar", self.lampString, prices[row]];
        } else {
            label.accessibilityLabel = [NSString stringWithFormat:@"%@-lampan kostar %@ kronor, du sparar då %.0f kronor på %ld år", self.lampString, prices[row], savings, (long)savingsCalculator.calculationYears];
        }
    }
    return label;
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    [savingsCalculator setPurchasePrice:[prices[row] floatValue] forSubstituteAtIndex:self.subtituteIndex];
    [self updateSavingsLabel];
    [self updateCostLabel];
}

-(void)updateSavingsLabel {
    CGFloat savings = [savingsCalculator savingsForSubstituteAtIndex:self.subtituteIndex];
    NSInteger years = savingsCalculator.calculationYears;
    if ([savingsCalculator savingsForSubstituteAtIndex:self.subtituteIndex] > 0) {
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Besparing: ca "];
        NSDictionary *boldGreenAttributes = @{ NSFontAttributeName:self.savingsLabel.font.boldFont,
                                               NSForegroundColorAttributeName:RGB(33, 151, 0)};
        [text appendAttributedString: [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.0f kr", savings] attributes:boldGreenAttributes]];
        [text appendAttributedString: [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@" på %ld år", (long)years]]];
        self.savingsLabel.attributedText = text;
    } else {
        self.savingsLabel.text = @"Besparing: ingen";
    }
    
    self.savingsLabel.accessibilityLabel = [self.savingsLabel.text stringByOptimizingForVoiceOver];
}

-(void)updateCostLabel {
    float cost = [savingsCalculator purchasePriceForSubstituteAtIndex:self.subtituteIndex];
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:@"Lampans inköpspris: "];
    NSDictionary *boldAttributes = @{ NSFontAttributeName:self.savingsLabel.font.boldFont };
    [text appendAttributedString: [[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%.0f kr", cost] attributes:boldAttributes]];
    self.costLabel.attributedText = text;
    self.costLabel.accessibilityLabel = [self.costLabel.text stringByOptimizingForVoiceOver];
}

-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [self updateViewForOrientation:toInterfaceOrientation];
}

@end
